package com.syni.mdd.sjb.common.datatreaure.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.dataBankBusiness.CdpUtilsBo;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.dataBankBusiness.OrderDeliveryTypeTotalBo;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.dataBankBusiness.SaleGoodTableDataBo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
public class CDPUtils {

    private static String appId = "appId";
    private static String appSecret = "appSecret";
    public static String superAccountId = "ff8080816a4d156a016a4e29e6b80006";

    @Value("${cdp.appId}")
    public void setAppId(String appId) {
        CDPUtils.appId = appId;
    }

    @Value("${cdp.appSecret}")
    public void setAppSecret(String appSecret) {
        CDPUtils.appSecret = appSecret;
    }

    public static void setRestTemplate(RestTemplate restTemplate) {
        CDPUtils.restTemplate = restTemplate;
    }

    private static  RestTemplate restTemplate;

    static{
        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(1000);
        httpComponentsClientHttpRequestFactory.setConnectTimeout(1000);
        httpComponentsClientHttpRequestFactory.setReadTimeout(1000);
        restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }



    public static String getAccessToken(){
        if(RedisTemplateUtils.hasKey(Constants.REDIS_KEY_CDP_ACCESS_TOKEN)){
            return RedisTemplateUtils.getRedisTemplate().opsForValue().get(Constants.REDIS_KEY_CDP_ACCESS_TOKEN).toString();
        }
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-auth/auth/base";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("appId",appId);
        paramsUrl.put("appSecret",appSecret);
        String responseBody = RestTemplateUtils.getForEntity(restTemplate,url,paramsUrl);
        Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
        if(ResultMapHelper.isSuccess(resultMap)){
            Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
            String accessToken = dataMap.get("accessToken").toString();
            RedisTemplateUtils.getRedisTemplate().opsForValue().set(Constants.REDIS_KEY_CDP_ACCESS_TOKEN,accessToken,30L, TimeUnit.MINUTES);
            return accessToken;
        }
        return "";
    }

    public static Integer countNumberOrdersProcessed(String accountId,Integer startTime,Integer endTime){

        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/pending-order-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startTime);
        paramsUrl.put("et",endTime);
        String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
        String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
        Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
        if(ResultMapHelper.isSuccess(resultMap)){
            Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");

        }
        return null;
    }


    public static void userPotentialUserTotal(CdpUtilsBo cdpUtilsBo,String accountId, String totalDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/user/potential-user-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("totalDate",totalDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("potentialUserQuantity")){
                    cdpUtilsBo.setPotentialUserQuantity(Integer.parseInt(dataMap.get("potentialUserQuantity").toString()));
                }
                if(dataMap.containsKey("potentialRevenue")){
                    cdpUtilsBo.setPotentialRevenue(Integer.parseInt(dataMap.get("potentialRevenue").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void activityActivityTotal(CdpUtilsBo cdpUtilsBo,String accountId, String totalDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/activity/activity-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("newNum") && StringUtils.checkNullAndEmpty(dataMap.get("newNum"))){
                    cdpUtilsBo.setNewNum(Integer.parseInt(dataMap.get("newNum").toString()));
                }
                if(dataMap.containsKey("activityQuantity") && StringUtils.checkNullAndEmpty(dataMap.get("activityQuantity"))){
                    cdpUtilsBo.setActivityQuantity(Integer.parseInt(dataMap.get("activityQuantity").toString()));
                }
                if(dataMap.containsKey("joinNum") && StringUtils.checkNullAndEmpty(dataMap.get("joinNum"))){
                    cdpUtilsBo.setJoinNum(Integer.parseInt(dataMap.get("joinNum").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void userCustomerTotal(CdpUtilsBo cdpUtilsBo,String accountId, String totalDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/user/customer-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("totalDate",totalDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("customerQuantity")){
                    cdpUtilsBo.setCustomerQuantity(Integer.parseInt(dataMap.get("customerQuantity").toString()));
                }
                if(dataMap.containsKey("revenue")){
                    cdpUtilsBo.setRevenue(Integer.parseInt(dataMap.get("revenue").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void userMemberTotal(CdpUtilsBo cdpUtilsBo,String accountId, String totalDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/user/member-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("totalDate",totalDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("memberQuantity")){
                    cdpUtilsBo.setMemberQuantity(Integer.parseInt(dataMap.get("potentialRevenue").toString()));
                }
                if(dataMap.containsKey("potentialRevenue")){
                    cdpUtilsBo.setMemberPotentialRevenue(Integer.parseInt(dataMap.get("potentialRevenue").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderPendingOrderTotal(CdpUtilsBo cdpUtilsBo,String accountId, String totalDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/pending-order-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",totalDate);
        paramsUrl.put("et",totalDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Integer data = Integer.parseInt(resultMap.get("data").toString());
                cdpUtilsBo.setBusinessKbOrdersProcessedNum(data);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderOrderTotal(CdpUtilsBo cdpUtilsBo, String accountId, String startDate, String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/order-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        if(StringUtils.isNotBlank(startDate)) {
            paramsUrl.put("st", startDate);
        }
        paramsUrl.put("et",endDate);
        paramsUrl.put("channel","微信小商店");
        paramsUrl.put("totalDimension","day");
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("totalAmount")){
                    cdpUtilsBo.setTotalAmount(Double.parseDouble(dataMap.get("totalAmount").toString()));
                }
                if(dataMap.containsKey("orderQuantity")){
                    cdpUtilsBo.setOrderQuantity(Integer.parseInt(dataMap.get("orderQuantity").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderOrderTotalGroup(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate,String group) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/order-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        if(StringUtils.isNotBlank(startDate)) {
            paramsUrl.put("st", startDate);
        }
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("totalDimension",group);
        paramsUrl.put("channel","微信小商店");
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("totalAmount")){
                    cdpUtilsBo.setTotalAmount(Double.parseDouble(dataMap.get("totalAmount").toString()));
                }
                if(dataMap.containsKey("orderQuantity")){
                    cdpUtilsBo.setOrderQuantity(Integer.parseInt(dataMap.get("orderQuantity").toString()));
                }
                if(dataMap.containsKey("totalList")){
                    JSONArray jsonArray = (JSONArray) dataMap.get("totalList");
                    if(jsonArray.size() > 0){
                        for(int ii = 0 ;ii < jsonArray.size();ii++){
                            JSONObject jsonObject = jsonArray.getJSONObject(ii);
                            Integer totalAmount = jsonObject.getInteger("totalAmount");
                            String totalDate = jsonObject.getString("totalDate");
                            cdpUtilsBo.getGroupLineData().put(totalDate, ArithUtil.round(totalAmount.doubleValue(),2));
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderDeliveryTypeTotal(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/delivery-type-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                JSONArray jsonArray = (JSONArray) resultMap.get("data");
                if(jsonArray.size() > 0){
                    for(int ii = 0;ii < jsonArray.size();ii++){
                        JSONObject jsonObject = jsonArray.getJSONObject(ii);
                        OrderDeliveryTypeTotalBo orderDeliveryTypeTotalBo = new OrderDeliveryTypeTotalBo();
                        orderDeliveryTypeTotalBo.setDeliveryType(jsonObject.getString("deliveryType"));
                        orderDeliveryTypeTotalBo.setOrderNumber(jsonObject.getInteger("orderNumber"));
                        cdpUtilsBo.getDeliveryTypeTotalBos().add(orderDeliveryTypeTotalBo);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void haveDinnerUserTotal(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = "/cdp/cdp-web-api/order/have-dinner-user-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        Map<String,Object> resultMap = commonCall(url,paramsUrl);
        if(ResultMapHelper.isSuccess(resultMap)){
            JSONArray jsonArray = (JSONArray) resultMap.get("data");
            if(jsonArray.size() > 0){
                for(int ii = 0;ii < jsonArray.size();ii++){
                    JSONObject jsonObject = jsonArray.getJSONObject(ii);
                    OrderDeliveryTypeTotalBo orderDeliveryTypeTotalBo = new OrderDeliveryTypeTotalBo();
                    orderDeliveryTypeTotalBo.setDeliveryType(jsonObject.getString("haveDinnerNumber"));
                    orderDeliveryTypeTotalBo.setOrderNumber(jsonObject.getInteger("orderNumber"));
                    cdpUtilsBo.getDeliveryTypeTotalBos().add(orderDeliveryTypeTotalBo);
                }
            }
        }
    }

    public static void OrderDeliveryDistanceTotal(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = "/cdp/cdp-web-api/order/delivery-distance-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        Map<String,Object> resultMap = commonCall(url,paramsUrl);
        if(ResultMapHelper.isSuccess(resultMap)){
            JSONArray jsonArray = (JSONArray) resultMap.get("data");
            if(jsonArray.size() > 0){
                for(int ii = 0;ii < jsonArray.size();ii++){
                    JSONObject jsonObject = jsonArray.getJSONObject(ii);
                    OrderDeliveryTypeTotalBo orderDeliveryTypeTotalBo = new OrderDeliveryTypeTotalBo();
                    orderDeliveryTypeTotalBo.setDeliveryType(jsonObject.getString("distanceType"));
                    orderDeliveryTypeTotalBo.setOrderNumber(jsonObject.getInteger("orderNumber"));
                    cdpUtilsBo.getDeliveryTypeTotalBos().add(orderDeliveryTypeTotalBo);
                }
            }
        }
    }

    public static void orderPerCustomerTransaction(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/per-customer-transaction";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                JSONArray jsonArray = (JSONArray) resultMap.get("data");
//                if(dataMap.containsKey("perCustomerTransaction")){
//                    cdpUtilsBo.setPerCustomerTransaction(Integer.parseInt(dataMap.get("perCustomerTransaction").toString()));
//                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderPerCustomerTransactionGroup(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate,String group) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/per-customer-transaction";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        if(StringUtils.isNotBlank(startDate)) {
            paramsUrl.put("st", startDate);
        }
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("totalDimension",group);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("totalAmount")){
                    cdpUtilsBo.setTotalAmount(Double.parseDouble(dataMap.get("totalAmount").toString()));
                }
                if(dataMap.containsKey("orderQuantity")){
                    cdpUtilsBo.setOrderQuantity(Integer.parseInt(dataMap.get("orderQuantity").toString()));
                }
                if(dataMap.containsKey("totalList")){
                    JSONArray jsonArray = (JSONArray) dataMap.get("totalList");
                    if(jsonArray.size() > 0){
                        for(int ii = 0 ;ii < jsonArray.size();ii++){
                            JSONObject jsonObject = jsonArray.getJSONObject(ii);
                            Integer totalAmount = jsonObject.getInteger("totalAmount");
                            String totalDate = jsonObject.getString("totalDate");
                            cdpUtilsBo.getGroupLineData().put(totalDate, ArithUtil.round(totalAmount.doubleValue(),2));
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void userAccessUserTotal(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/user/access-user-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        paramsUrl.put("totalDimension","day");
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("userQuantity")){
                    cdpUtilsBo.setUserQuantity(Integer.parseInt(dataMap.get("userQuantity").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 成交转化率
     * @param cdpUtilsBo
     * @param accountId
     * @param startDate
     * @param endDate
     */
    public static void orderPayConversionRate(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/pay-conversion-rate";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("payRate")){
                    cdpUtilsBo.setPayRate(Double.parseDouble(dataMap.get("payRate").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 成交转化率
     * @param cdpUtilsBo
     * @param accountId
     * @param startDate
     * @param endDate
     */
    public static void userAccessUserTotalGroup(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate,String totalDimension) {
        String url = "/cdp/cdp-web-api/user/access-user-total";
        Map<String,Object> params = new HashMap<>();
        params.put("accountId",accountId);
        params.put("st",startDate);
        params.put("et",endDate);
        params.put("totalDimension",totalDimension);
        Map<String,Object> resultMap =commonCall(url,params);
        if(ResultMapHelper.isSuccess(resultMap)){
            Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
            if(dataMap.containsKey("totalList")){
                JSONArray jsonArray = (JSONArray) dataMap.get("totalList");
                if(jsonArray.size() > 0){
                    for(int ii = 0 ;ii < jsonArray.size();ii++){
                        JSONObject jsonObject = jsonArray.getJSONObject(ii);
                        Integer totalAmount = jsonObject.getInteger("userQuantity");
                        String totalDate = jsonObject.getString("totalDate");
                        cdpUtilsBo.getGroupLineData().put(totalDate, ArithUtil.round(totalAmount.doubleValue(),2));
                    }
                }
            }
        }
    }

    public static void orderPerCustomerTransactionType(CdpUtilsBo cdpUtilsBo,String accountId,Integer day){
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/per-customer-transaction-type";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("days",day);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("perCustomerTransaction")){
                    cdpUtilsBo.setPerCustomerTransaction(Integer.parseInt(dataMap.get("perCustomerTransaction").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void orderAccessConversionRate(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/access-conversion-rate";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("accessRate")){
                    cdpUtilsBo.setAccessRate(Double.parseDouble(dataMap.get("accessRate").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 下单转化率
     * @param cdpUtilsBo
     * @param accountId
     * @param startDate
     * @param endDate
     */
    public static void orderPayOrderRate(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate) {
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/order/pay-order-rate";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                Map<String,Object> dataMap = (Map<String, Object>) resultMap.get("data");
                if(dataMap.containsKey("payOrderRate")){
                    cdpUtilsBo.setPayOrderRate(Double.parseDouble(dataMap.get("payOrderRate").toString()));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 商品销售排行
     * @param cdpUtilsBo
     * @param accountId
     * @param startDate
     * @param endDate
     */
    public static void productSaleTotal(CdpUtilsBo cdpUtilsBo,String accountId, String startDate,String endDate){
        cdpUtilsBo.getProductSaleNum().clear();
        cdpUtilsBo.getProductSaleNumMap().clear();
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/product/sale-total";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("st",startDate);
        paramsUrl.put("et",endDate);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                //模拟数据
//                if(ApplicationContextHolder.checkRunProfile("preo")) {
//                    List<SaleGoodTableDataBo> saleGoodTableDataBos = new LinkedList<>();
//                    SaleGoodTableDataBo saleGoodTableDataBo_test1 = new SaleGoodTableDataBo();
//                    saleGoodTableDataBo_test1.setProductName("山楂");
//                    saleGoodTableDataBo_test1.setProductQuantity(800);
//                    saleGoodTableDataBo_test1.setProductId("1");
//
//                    SaleGoodTableDataBo saleGoodTableDataBo_test2 = new SaleGoodTableDataBo();
//                    saleGoodTableDataBo_test2.setProductName("草药");
//                    saleGoodTableDataBo_test2.setProductQuantity(20);
//                    saleGoodTableDataBo_test2.setProductId("2");
//
//
//                    saleGoodTableDataBos.add(saleGoodTableDataBo_test1);
//                    saleGoodTableDataBos.add(saleGoodTableDataBo_test2);
//
//                    resultMap.put("data", JSON.parseArray(JSON.toJSONString(saleGoodTableDataBos)));
//
//                }
                JSONArray dataMap = (JSONArray) resultMap.get("data");
                if (dataMap.size() > 0) {
                    for(int ii = 0;ii < dataMap.size();ii++){
                        JSONObject jsonObject = dataMap.getJSONObject(ii);
                        SaleGoodTableDataBo saleGoodTableDataBo = new SaleGoodTableDataBo();
                        saleGoodTableDataBo.setProductId(jsonObject.getString("productId"));
                        saleGoodTableDataBo.setProductName(jsonObject.getString("productName"));
                        saleGoodTableDataBo.setProductQuantity(Integer.parseInt(jsonObject.getString("productQuantity")));
                        cdpUtilsBo.getProductSaleNum().add(saleGoodTableDataBo);
                        cdpUtilsBo.getProductSaleNumMap().put(saleGoodTableDataBo.getProductId(),saleGoodTableDataBo.getProductQuantity());
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {

        }
    }

    public static void productRepurchaseBuyRate(CdpUtilsBo cdpUtilsBo,String accountId, String days){
        String url = AppConfig.getProperty("cdp.domain") + "/cdp/cdp-web-api/product/repurchase-buy-rate";
        Map<String,Object> paramsUrl = new HashMap<>();
        paramsUrl.put("accountId",accountId);
        paramsUrl.put("days",days);
        try {
            String postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            Map<String,Object> resultMap = JSON.parseObject(responseBody,Map.class);
            if(ResultMapHelper.isSuccess(resultMap)){
                //模拟数据
//                if(ApplicationContextHolder.checkRunProfile("preo")) {
//                    List<SaleGoodTableDataBo> saleGoodTableDataBos = new LinkedList<>();
//                    SaleGoodTableDataBo saleGoodTableDataBo_test1 = new SaleGoodTableDataBo();
//                    saleGoodTableDataBo_test1.setProductName("山楂");
//                    saleGoodTableDataBo_test1.setProductQuantityRate(30);
//                    saleGoodTableDataBo_test1.setProductId("1");
//
//                    SaleGoodTableDataBo saleGoodTableDataBo_test2 = new SaleGoodTableDataBo();
//                    saleGoodTableDataBo_test2.setProductName("草药");
//                    saleGoodTableDataBo_test2.setProductQuantityRate(50);
//                    saleGoodTableDataBo_test2.setProductId("2");
//
//                    saleGoodTableDataBos.add(saleGoodTableDataBo_test1);
//                    saleGoodTableDataBos.add(saleGoodTableDataBo_test2);
//
//                    resultMap.put("data", JSON.parseArray(JSON.toJSONString(saleGoodTableDataBos)));
//                }

                JSONArray dataMap = (JSONArray) resultMap.get("data");
                if (dataMap.size() > 0) {
                    for(int ii = 0;ii < dataMap.size();ii++){
                        JSONObject jsonObject = dataMap.getJSONObject(ii);
                        SaleGoodTableDataBo saleGoodTableDataBo = new SaleGoodTableDataBo();
                        saleGoodTableDataBo.setProductId(jsonObject.getString("productId"));
                        saleGoodTableDataBo.setProductName(jsonObject.getString("productName"));
                        saleGoodTableDataBo.setProductQuantityRate(jsonObject.getInteger("productQuantityRate") == null ? 0 : jsonObject.getInteger("productQuantityRate"));
                        cdpUtilsBo.getProductQuantityRate().add(saleGoodTableDataBo);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static Map<String,Object> commonCall(String postUrl,Map<String,Object> paramsUrl) {
        String url = AppConfig.getProperty("cdp.domain") + postUrl;
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put(ResultCode.CODE_ERROR, ResultMsg.ADMIN_ERROR);
        try {
            postUrl = String.format("%s?accessToken=%s",url,getAccessToken());
            String responseBody = RestTemplateUtils.postForEntityForJson(restTemplate,postUrl,paramsUrl);
            resultMap = JSON.parseObject(responseBody,Map.class);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }


}
